package com.wap.framework.admin.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.wap.framework.model.AdminUser;
import com.wap.framework.service.LoginService;
import com.wap.framework.util.Constants;

public class LoginAction extends Action {

	private LoginService loginService;

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String key = request.getParameter("key");
		if (key == null || "".equals(key)) {
			return mapping.findForward("fwd_no_auth");
		}

		HttpSession session = request.getSession();
		LoginForm loginForm = (LoginForm) form;
		String username = loginForm.getUsername();
		String password = loginForm.getPassword();

		if (username == null || "".equals(username) || password == null
				|| "".equals(password)) {
			return mapping.getInputForward();
		}

		AdminUser au = loginService.login(username, password);
		if (au == null) {
			return mapping.getInputForward();
		} else {
			session.setAttribute(Constants.ADMIN_TOKEN, au);
			return mapping.findForward("success");
		}
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
}
